<html>
<title>Query</title>
<body>

<!-- This is an HTML comment. -->
<h1>SQL Query</h1>
<p>Type an SQL query into the following box. SHOW and SELECT queries only (case insensitive), ";" at the end of the query is optional, and tables/fields case sensitive.</p>
<p>Assume all user inputs are correct and can be trusted.</p>
<p>
<form method="GET">
<textarea name="expr" cols="60" rows="8"></textarea>
<input type="submit" value="Query">
</form>
</p>

<h2>Query Result</h2>
<?php
	$expr = $_GET["expr"];
	$db_connection = mysql_connect("localhost", "cs143", "");
	if (!db_connection)
	{
		$errmsg = mysql_error($db_connection);
		echo "Connection failed: $errmsg <br />";
		exit(1);
	}
	
	$query = $expr;
	mysql_select_db("CS143", $db_connection);
	$rs = mysql_query($query, $db_connection);
	
	if ($rs == false) // if error, then unsuccessful
	{
		echo "Invalid SQL query.";
	}
	else // successful query
	{
		$num_cols = mysql_num_fields($rs);
		$num_rows = mysql_num_rows($rs); // might not need this
		
		// print column names
		echo "<table border=1 cellspacing=1 cellpadding=2><tr align=center>";
		for ($i=0; $i<$num_cols; $i++)
		{
			$field_name = mysql_field_name($rs, $i);
			echo "<td><b>$field_name</b></td>";
		}
		echo "</tr>";
		
		// print each row
		while ($row = mysql_fetch_row($rs))
		{
			echo "<tr align=center>";
			for ($i=0; $i<$num_cols; $i++)
			{
				$column = $row[$i];
				if ($column == NULL)
					$column = "N/A";
				echo "<td>$column</td>";
			}
			echo "</tr>";
		}
		echo "</table>";
	}
	
	mysql_close($db_connection);
?>

</body>
</html>